package help.qaq.baoxiang;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;

public class Baoxiang extends JavaPlugin implements Listener
{
      private List<String> chestslist;
	  private List<String> itemslist;
	  public void onEnable() {
		    getServer().getPluginManager().registerEvents(this, this);
		    if(!getDataFolder().exists()) {
		        getDataFolder().mkdir();
		        }
		    File file=new File(getDataFolder(),"config.yml");
	        if (!(file.exists())) {saveDefaultConfig();}
	        getConfigCon();
	        getLogger().info("插件载入成功");
	  }
	  public void onDiscable() {
	    getLogger().info("插件卸载成功");
	    HandlerList.unregisterAll(); 
	  }
	  public void getConfigCon()
	  {
	    this.itemslist = getConfig().getStringList("Items");
	    this.chestslist = getConfig().getStringList("Chests");
	  }
	  public void addItems(String itemTypeString , Player p) {;
		    if(itemslist.contains(itemTypeString))
		    {
			     p.sendMessage("§c物品已被添加！");
		    }else{		    
			 itemslist.add(itemTypeString);
			 getConfig().set("Items",itemslist);
			 File file=new File(getDataFolder(),"config.yml");
			 try{getConfig().save(file);}
			          catch
			          (IOException e){e.printStackTrace();}
		     p.sendMessage("§a添加物品成功！");
			 }
		     getConfigCon();
	  }
	  public void removeItems(String itemTypeString , Player p){
		    if(!(itemslist.contains(itemTypeString)))
		    {
			     p.sendMessage("§c物品不存在列表中！");
		    }else{	
		    	itemslist.remove(itemTypeString);
		   getConfig().set("Items", itemslist);
		   File file = new File (getDataFolder(),"config.yml");
		   try{getConfig().save(file);}
		           catch
		           (IOException e){e.printStackTrace();}
			 p.sendMessage("§a删除物品成功！");

	  }
		     getConfigCon();
}
	 public void newChest (String xyz, Player p){    
		     if(chestslist.contains(xyz)){
			     chestslist.remove(xyz);
				 getConfig().set("Chests",chestslist);
				 File file=new File(getDataFolder(),"config.yml");
				 try{getConfig().save(file);}
				          catch
				          (IOException e){e.printStackTrace();}
			     p.sendMessage("§c删除箱子成功！");
		     }else{
			     chestslist.add(xyz);
				 getConfig().set("Chests",chestslist);
				 File file=new File(getDataFolder(),"config.yml");
				 try{getConfig().save(file);}
				          catch
				          (IOException e){e.printStackTrace();}
			     p.sendMessage("§a添加箱子成功！"); 
		     }
		     getConfigCon();
			 		 
	 }
	@SuppressWarnings("deprecation")
	@EventHandler
    public void PlayerInteractBlock(PlayerInteractEvent evt){
	     Player p = evt.getPlayer();
    		if(evt.getAction() == Action.RIGHT_CLICK_BLOCK &&
    				chestslist.contains(evt.getPlayer().getTargetBlock(null, 4).getLocation().toString())   				
    				){	
    			       if(!(evt.getPlayer().getTargetBlock(null, 4).getType().toString().contains("CHEST"))){
    			    	   p.sendMessage("§c这个位置的箱子似乎并不存在，已经自动在列表删除");
  					       Block block = evt.getPlayer().getTargetBlock(null, 4);
    				       newChest(block.getLocation().toString(),p);
    			       }else{
    			    	    Inventory inv1 = Bukkit.createInventory(null,InventoryType.CHEST , "宝箱");
    			    	    int length = itemslist.size();
    			    	    int index = 0;
    			    	    for(int i=0;i<length;i++){
    			    	        index++;
    			    	        int id =  Integer.valueOf(i).intValue();
        			    	    ItemStack myitem = new ItemStack(id);
        			    	    inv1.setItem(index , myitem); 
    			    	    }
    		                p.closeInventory();
    		                evt.setCancelled(true);
    		                p.openInventory(inv1);
    			       }
    		}
    	if(evt.getPlayer().getItemInHand().getType() == Material.STICK){
    		if(evt.getAction() == Action.LEFT_CLICK_BLOCK && evt.getPlayer().getTargetBlock(null, 4).getType().toString().contains("CHEST")){	
					     Player pl = evt.getPlayer();
					     Block block = evt.getPlayer().getTargetBlock(null, 4);
    				     newChest(block.getLocation().toString(),pl);
    			}
    		}
    	}
     
	public boolean onCommand(CommandSender sender,Command cmd,String label,String[] args){
		 if(cmd.getName().equalsIgnoreCase("bx")) {
			 Player p = (Player)sender;
		      if (args.length == 0) {
		          sender.sendMessage(ChatColor.BLUE + "==================宝箱插件====================");
		          sender.sendMessage("/bx additem 物品id 增加一个物品 ，不填即添加手上物品。");
		          sender.sendMessage("/bx delitem 物品id 移除一个物品，不填即删除手上物品。");
		          sender.sendMessage("使用§c木棒§f左击箱子可以把他添加或删除");
		          sender.sendMessage(ChatColor.BLUE + "=============================================");
		          return true;
		        }
			 if (args[0].equalsIgnoreCase("additem") && ((sender instanceof Player))) {				 
				     if(args.length == 2 ){
				    	 addItems(args[1],p);
				    	 return true;
				    	 }
					 @SuppressWarnings("deprecation")
					 int newItem = p.getItemInHand().getTypeId();
					 String sItem = String.valueOf(newItem);
					 addItems(sItem,p);
					 return true;            
			 } 
			 if (args[0].equalsIgnoreCase("delitem") && ((sender instanceof Player))) {				 
			     if(args.length == 2 ){
			    	 removeItems(args[1],p);
			    	 return true;
			     }
				 @SuppressWarnings("deprecation")
				 int newItem = p.getItemInHand().getTypeId();
				 String sItem = String.valueOf(newItem);
				 removeItems(sItem,p);
				 return true;            
		 } 
	  
		 }
    	  return false;    	  
      } 
}
